package org.appFactory.carleton;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.appFactory.shared.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("serial")
public class AppManager extends CarletonBaseListener implements ServletResponseAware {

	private HttpServletResponse response = null;
		
	private JSONObject events;
	
	private InputStream inputStream;
	
	private String latitude;
	
	private String longitude;
	
	private String accessToken;
	
	private String type;
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getLatitude() {
		return latitude;
	}

	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public InputStream getInputStream() {
	    return inputStream;
	} 

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletResponse getServletResponse() {
		return this.response;
	}
	
	public JSONObject getEvents() {
		return events;
	}
	
	
	public String execute() {
		
			if(type == null || type.equals("events")) {
				//Check Cache = TBD
				
				//Case : Cache Miss
				//Fetch Events - Real-time
				System.out.println("Computing Events for " + latitude +"," + longitude);
				//events = getFacebookService().getEvents(latitude, longitude, 1000);
				events = Util.fetchJSONEvents(latitude, longitude, "1");
				try {
					if (events.getJSONArray("data").length() < 2) {
						    System.out.println("Cache Missed for " + latitude +"," + longitude);
							events = getFacebookService().getEvents(latitude, longitude, 1000);
							System.out.println("Starting Caching for " + latitude +"," + longitude);
							Util.insertJSONEvents(events);
							System.out.println("Finished Caching for " + latitude +"," + longitude);
					}
					else 
					    System.out.println("Cache Hit for " + latitude +"," + longitude);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(events.toString());
				inputStream = new ByteArrayInputStream(events.toString().getBytes());
				System.out.println("Finished Task for " + latitude +"," + longitude);
				//Save Events on Cache 
				//Util.insertJSONEvents(events);

				return SUCCESS;
			}				
			
			return ERROR;
	
	}

}
